<template>
	<view class="page-container">
		<view class="post-list" v-if="posts.length">
			<view class="post-card" v-for="post in posts" :key="post.id">
				<view class="post-header">
					<image class="avatar" :src="post.userAvatar" mode="aspectFill"></image>
					<text class="username">{{post.username}}</text>
					<text class="post-time">{{post.createTime}}</text>
				</view>

				<text class="post-content">{{post.content}}</text>

				<view class="post-images" v-if="post.images">
					<image :src="post.images" mode="aspectFill" @click="previewImage([post.images])"></image>
				</view>
			</view>
		</view>

		<view class="empty-container" v-else>
			<text class="empty-text">暂无数据</text>
			<button class="empty-btn" @click="goPage">请发布您的第一篇</button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		apiGetPosts
	} from "@/api/apis.js"
	import {
		onLoad
	} from '@dcloudio/uni-app'

	const posts = ref([])

	const loadPosts = async () => {
		try {
			let user;
			// #ifdef MP
			user = uni.getStorageSync("userInfo");
			// #endif
			// #ifndef MP
			user = JSON.parse(uni.getStorageSync("userInfo") || "{}");
			// #endif

			const res = await apiGetPosts({
				userId: user.id
			})
			posts.value = res.data || []
		} catch (e) {
			console.error(e)
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		}
	}

	const previewImage = (urls) => {
		uni.previewImage({
			urls
		})
	}

	onLoad(() => {
		loadPosts()
	})

	const goPage = () => {
		uni.switchTab({
			url: '/pages/circle/circle'
		})
	}
</script>

<style lang="scss" scoped>
	.page-container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.post-list {
		display: flex;
		flex-direction: column;
		gap: 24rpx;
	}

	.post-card {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 28rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.post-header {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;

		.avatar {
			width: 72rpx;
			height: 72rpx;
			border-radius: 50%;
			margin-right: 16rpx;
		}

		.username {
			font-size: 30rpx;
			font-weight: 500;
			color: #333;
			flex: 1;
		}

		.post-time {
			font-size: 24rpx;
			color: #999;
		}
	}

	.post-content {
		font-size: 28rpx;
		color: #333;
		line-height: 1.6;
		margin-bottom: 24rpx;
	}

	.post-images {
		image {
			width: 100%;
			height: 300rpx;
			border-radius: 8rpx;
			background-color: #eee;
		}
	}

	.empty-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 60vh;

		.empty-text {
			font-size: 28rpx;
			color: #999;
			margin-bottom: 30rpx;
		}

		.empty-btn {
			width: 500rpx;
			height: 70rpx;
			line-height: 70rpx;
			font-size: 28rpx;
			background-color: #007aff;
			color: #fff;
			border-radius: 35rpx;
		}
	}
</style>